package com.his.his_system.controller.VisitController;
import cn.hutool.json.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.his.his_system.common.util.ResultAdvice;
import com.his.his_system.controller.VisitController.DefaultBean.RegisterAndSchen;
import com.his.his_system.controller.VisitController.DefaultBean.Schenduling;
import com.his.his_system.domain.*;
import com.his.his_system.service.*;
import jdk.nashorn.internal.objects.annotations.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

/**
 * 门诊挂号
 * 余襄元
 */
@RestController
@RequestMapping("/his/sad/register/")
@Slf4j
public class RegistrationController {

    @Resource
    private DefaultService defaultService;

    @Resource
    private DzmPatientService dzmPatientService;

    @Resource
    private DzmHisRegistrationService dzmHisRegistrationService;

    @Resource
    private DzmHisCarePkgService dzmHisCarePkgService;

    @Resource
    private  YxyTodo yxyTodo;

    @Resource
    private DzmHisCarePaylogService dzmHisCarePaylogService;

    @Resource
    private HttpServletResponse resp;

    /**
     * 获取患者列表
     * @return
     */
    @GetMapping("getPatientList")
    public ResultAdvice<List<DzmPatient>> getPatientList(){
        return ResultAdvice.success(dzmPatientService.list(),"成功");
    }


    /**
     * 根据姓名和电话获取患者
     * @param name
     * @param php
     * @return
     */
    @PostMapping("getPatientListBynameAndphp")
    public ResultAdvice<List<DzmPatient>> getPatientListBynameAndphp(String name,String php){
        QueryWrapper<DzmPatient> queryWrapper = new QueryWrapper();
        queryWrapper.like("name",name).like("mobile",php);
        return ResultAdvice.success(dzmPatientService.list(queryWrapper),"成功");
    }

    /**
     * 获取可预约的的排班信息
     * @return
     */
    @GetMapping("getAllSchedulingByNow")
    public ResultAdvice<List<Schenduling>> getAllSchedulingByNow(){

        return ResultAdvice.success(defaultService.getAllSchedulingByNow(null,null,null),"成功");
    }


    /**
     * 患者挂号 -支付
     * @param registerAndSchen
     * @return
     */
    @PostMapping("FristRegisterLastPay")
    @Transactional
    public ResultAdvice FristRegisterLastPay(@RequestBody RegisterAndSchen registerAndSchen){
           Integer staut=0;
           if(registerAndSchen.getPay()==1){
               staut=1;
           }else {
               staut=5;
           }
        DzmHisRegistration dzmHisRegistration= new DzmHisRegistration();
        Integer pid=registerAndSchen.getPatientId();
        if(!registerAndSchen.getDisabled()){
           if(selectPatient(registerAndSchen.getPhp())){
               return ResultAdvice.fail("该手机号已被注册！");
           }
            DzmPatient dzmPatient = new DzmPatient();
            insrefPatient(dzmPatient,registerAndSchen);
              if(dzmPatientService.save(dzmPatient)){
                  pid=dzmPatient.getPatientId();
              }else {
                  return ResultAdvice.fail("添加失败，系统异常请稍后重试");
              }
        }
        FristPay(dzmHisRegistration,registerAndSchen,staut,pid);
        QueryWrapper<DzmHisRegistration> queryWrapper = new QueryWrapper();
        queryWrapper.eq("patient_id",dzmHisRegistration.getPatientId());
        queryWrapper.eq("scheduling_week_id",dzmHisRegistration.getSchedulingWeekId());
        queryWrapper.eq("scheduling_subsection_id",dzmHisRegistration.getSchedulingSubsectionId());
        queryWrapper.eq("scheduling_id",dzmHisRegistration.getSchedulingId());
        queryWrapper.eq("company_id",dzmHisRegistration.getCompanyId());
        queryWrapper.eq("department_id",dzmHisRegistration.getDepartmentId());
        queryWrapper.eq("physician_id",dzmHisRegistration.getPhysicianId());
        List<DzmHisRegistration> list=dzmHisRegistrationService.list(queryWrapper);
        if(list.size()>0){
            return ResultAdvice.fail("该用户已经挂号了科室医生");
        }
        Boolean fig = dzmHisRegistrationService.save(dzmHisRegistration);
        //已支付账单
        if(staut==1){
            DzmHisCarePkg dzmHisCarePkg = new DzmHisCarePkg();
            insrefdzmHisCarePkg(dzmHisCarePkg,dzmHisRegistration,1);
            if(!dzmHisCarePkgService.save(dzmHisCarePkg)){
                return ResultAdvice.fail("添加已支付账单，系统异常请稍后重试");
            }
            try{
                DzmHisCarePaylog dzmHisCarePaylog =new DzmHisCarePaylog();
                dzmHisCarePaylog.setPaymentPlatform(1);
                dzmHisCarePaylog.setPayAmount(BigDecimal.valueOf(registerAndSchen.getRegisteredfeeAggregateAmount()));
                dzmHisCarePaylog.setStatus(1);
                dzmHisCarePaylog.setAddtime((int)(System.currentTimeMillis()/1000));
                if(!dzmHisCarePaylogService.save(dzmHisCarePaylog)){
                    log.error("添加付款记录失败");
                    return ResultAdvice.fail("挂号失败");
                }
            }catch (Exception e){
                log.error("添加付款记录失败");
                return ResultAdvice.fail("挂号失败");
            }


        }
        //未支付账单
        if(staut==5){
            DzmHisCarePkg dzmHisCarePkg = new DzmHisCarePkg();
            insrefdzmHisCarePkg(dzmHisCarePkg,dzmHisRegistration,0);
            if(!dzmHisCarePkgService.save(dzmHisCarePkg)){
                return ResultAdvice.fail("添加未支付账单，系统异常请稍后重试");
            }
        }
        return ResultAdvice.success(fig,"添加成功");
    }


    //模糊查询
    @GetMapping("selectsched")
    public ResultAdvice<List<Schenduling>> selectsched(String doctorname ){
        return ResultAdvice.success(defaultService.selectsched(doctorname));
    }

    //患者添加挂号
    public void FristPay(DzmHisRegistration dzmHisRegistration,RegisterAndSchen registerAndSchen ,int Status,Integer Patientid){
        dzmHisRegistration.setPatientId(Patientid);
        dzmHisRegistration.setPhysicianId(registerAndSchen.getId());
        dzmHisRegistration.setOperatorId(yxyTodo.getUserid());
        dzmHisRegistration.setCompanyId(yxyTodo.getHospitalid());
        dzmHisRegistration.setDepartmentId(registerAndSchen.getDid());
        dzmHisRegistration.setRegisteredfeeId(registerAndSchen.getRegId());
        dzmHisRegistration.setRegistrationAmount(registerAndSchen.getRegisteredfeeAggregateAmount());
        dzmHisRegistration.setRegistrationNumber(Long.parseLong("2017113000001000"+Patientid));
        dzmHisRegistration.setRegistrationStatus(Status);
        dzmHisRegistration.setSchedulingId(registerAndSchen.getSchedulingId());
        dzmHisRegistration.setSchedulingSubsectionId(registerAndSchen.getSchedulingSubsectionId());
        dzmHisRegistration.setSchedulingWeekId(registerAndSchen.getSchedulingWeekId());
        dzmHisRegistration.setCreateTime((int)(System.currentTimeMillis()/1000));
        dzmHisRegistration.setUpdateTime((int)(System.currentTimeMillis()/1000));
    }

    //添加患者
    public void insrefPatient(DzmPatient dzmPatient,RegisterAndSchen registerAndSchen){
        dzmPatient.setHospitalId(yxyTodo.getHospitalid());
        dzmPatient.setName(registerAndSchen.getName());
        dzmPatient.setMobile(registerAndSchen.getPhp());
        dzmPatient.setUpdateTime((int)(System.currentTimeMillis()/1000));
        dzmPatient.setSex(Integer.valueOf(registerAndSchen.getSex()));
        dzmPatient.setBirthday(registerAndSchen.getAge());
        dzmPatient.setIdCard(registerAndSchen.getIdcard());
        dzmPatient.setIsFinal(0);
        dzmPatient.setAddress(registerAndSchen.getAddress());
        dzmPatient.setCreateTime((int)(System.currentTimeMillis()/1000));
        dzmPatient.setIsDel(0);
    }

    //添加之前先查询是否有重复的
    public boolean selectPatient(String php){
        QueryWrapper<DzmPatient> queryWrapper = new QueryWrapper();
        queryWrapper.eq("mobile",php);
        DzmPatient dzmPatient= dzmPatientService.getOne(queryWrapper);
        if(dzmPatient==null){
            return false;
        }else {
            return true;
        }
    }

    //付费
    public void insrefdzmHisCarePkg(DzmHisCarePkg dzmHisCarePkg,DzmHisRegistration dzmHisRegistration,Integer staut){
        dzmHisCarePkg.setHospitalId(yxyTodo.getHospitalid());
        dzmHisCarePkg.setDoctorId(dzmHisRegistration.getPhysicianId());
        dzmHisCarePkg.setPatientId(dzmHisRegistration.getPatientId());
        //TODO 就诊完修改添加 病例id
        dzmHisCarePkg.setRegistrationId(dzmHisRegistration.getRegistrationId());
        dzmHisCarePkg.setOrderCode(System.currentTimeMillis()+"");
        dzmHisCarePkg.setAmount( new BigDecimal(Double.toString(dzmHisRegistration.getRegistrationAmount())));
        dzmHisCarePkg.setTypeId(1);
        dzmHisCarePkg.setStatus(staut);
        dzmHisCarePkg.setAddtime(System.currentTimeMillis()/1000);
        dzmHisCarePkg.setOpPlace(4);
    };

    /**
     * 获取所有病例
     * @param name
     * @param depname
     * @return
     */
    @GetMapping("getAllHistory")
    public ResultAdvice getAllHistory(String name,String depname){
      return  ResultAdvice.success(defaultService.getAllHistory(name,depname),"成功");
    }
}
